<template>
  <div>
    <!-- 搜索结果页-头部导航 -->
    <div class="search-result-container">
      <!-- 点击实现后退效果 -->
      <van-nav-bar
        title="搜索结果"
        left-arrow
        @click-left="$router.go(-1)"
        fixed
      />
    </div>
    <!-- 搜索结果 -->
    <div>
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :immediate-check="false"
        offset="50"
      >
        <ArticleItem
          v-for="obj in articleList"
          :key="obj.art_id"
          :obj="obj"
          :showX="false"
          @click.native="$router.push(`/article_detail?aid=${obj.art_id}`)"
        ></ArticleItem>
      </van-list>
    </div>
  </div>
</template>

<script>
import { timeAgo } from '@/utils/date'

import { searchResultListAPI } from '@/api'
import ArticleItem from '../Home/components/ArticleItem.vue'

export default {
  name: 'SearchResult',
  data () {
    return {
      articleList: [],
      loading: false,
      finished: false,
      page: 1 // 页码
    }
  },
  async created () {
    this.getSearchResultFn()
  },
  methods: {
    onLoad () {
      if (this.articleList.length > 0) {
        this.page++
        this.getSearchResultFn()
      }
    },
    // 获取搜索结果
    async getSearchResultFn () {
      const res = await searchResultListAPI({
        q: this.$route.params.keyword // 拿到关键词, keywords来源于router/index.js你定义的动态路由参数名
      })
      console.log(res)
      if (res.data.data.results.length === 0) {
        this.finished = true
        return
      }
      // 数据预处理
      res.data.data.results.forEach((obj) => {
        obj.pubdate = timeAgo(obj.pubdate)
      })
      // 合并数据
      this.articleList = [...this.articleList, ...res.data.data.results]
      this.loading = false
    }
  },
  components: { ArticleItem }
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
</style>
